package com.xxl.job.admin.core.alarm;

import cn.hutool.json.JSONUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description: 发送钉钉通知
 * @Author: Ning
 * @Date: 2022/4/12 10:10
 */
@Service
@Slf4j
public class DingMessagePushManager {


    @Autowired
    private DingProperties dingProperties;

    /**
     * 钉钉通知
     *
     * @param message
     */
    @Async
    public void sendDing(String message, List<String> mobiles) throws ApiException {
        try {
            Long timestamp = System.currentTimeMillis();
            String sign = sign(timestamp, dingProperties.getSecret());
            String url = String.format(dingProperties.getUrl(), timestamp, sign);
            DingTalkClient client = new DefaultDingTalkClient(url);
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent(message);
            request.setText(text);
            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            if (null != mobiles && mobiles.size() > 0) {
                at.setAtMobiles(mobiles);
                at.setIsAtAll(false);
            } else {
                at.setIsAtAll(true);
            }
            request.setAt(at);
            OapiRobotSendResponse response = client.execute(request);
            log.info(JSONUtil.toJsonStr(response));
        } catch (Exception e) {
            log.error("钉钉机器人失败", e);
        }
    }

    public static String sign(Long timestamp, String secret) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData,false)), "UTF-8");
        System.out.println(sign);
        return sign;
    }
}
